import constants from '../../common/app/constant.js';
import Config from '../../common/app/config.js';
import Constant from '../../common/app/constant.js';
import {strings} from '../../i18n/zh-CN.json';
import StorageNative from '../../common/app/storageNative.js';

export default {
    data: {
        currentMode: 0, //0:经典模式  1:无限模式
        currentModeDesc: "",
        bestScoreTitle: "最高分",
        bestScore: 0,
        currentScore: 0,
        isNeedSave: true,
        tempDifficultySelected: 0, //难度选择临时变量
        diffcults: [
            {
                "id": "1001",
                "name": "4 x 4",
                "level": 4,
                "checked": true
            },
            {
                "id": "1002",
                "name": "5 x 5",
                "level": 5,
                "checked": false
            },
            {
                "id": "1003",
                "name": "6 x 6",
                "level": 6,
                "checked": false
            }
        ],
        tempSoundsSelected: -1, //音效选择临时变量
        sounds: [
            {
                index: 0,
                "checked": true,
                "name": "开启",
                "state": "open"
            },
            {
                index: 1,
                "checked": false,
                "name": "关闭",
                "state": "close"
            }
        ],
        achievements: strings.achievements,
        gameOverResult: 'You Win!'
    },
    onInit() {
        this.initData();
        let _this = this;
        setInterval(() => {
            if (_this.isNeedSave) {
                // 5S保存一次游戏进度
                _this.saveGameProgress();
            }
        }, 5000);
    },
    async initData() {
        let that = this;
        // 获取到游戏难度
        var gameDifficultyStr = await StorageNative.getGameDifficulty();
        var gameDifficulty = JSON.parse(gameDifficultyStr);
        if (gameDifficulty.code == 0) {
            Config.GRIDColumnCount = gameDifficulty.result;
        }
        // 获取到最高分
        var data = await StorageNative.getBestScore();
        console.log("=== StorageNative getBestScore " + data);
        var obj = JSON.parse(data);
        if (obj.code == 0) {
            Config.BestScore = obj.result;
            this.bestScore = Config.BestScore;
        }
        // 获取游戏音效状态
        var gameVolumeStateStr = await StorageNative.getGameVolumeState();
        var gameVolumeState = JSON.parse(gameVolumeStateStr);
        if (gameVolumeState.code == 0) {
            Config.VolumeState = gameVolumeState.result;
        }
        // 获取达成游戏目标次数
        var goalTimeStr = await StorageNative.getGoalTime();
        var goalTime = JSON.parse(goalTimeStr);
        if (goalTime.code == 0) {
            console.log("===goalTime: " + goalTime.result);
            Config.GetGoalTime = goalTime.result;
        }
        // 获取游戏模式
        var currentGameModeStr = await StorageNative.getCurrentGameMode();
        var currentGameMode = JSON.parse(currentGameModeStr);
        if (currentGameMode.code == 0) {
            Config.CurrentGameMode = currentGameMode.result;
        }
        // 获取无限模式下最高分
        var bestScoreWithinInfiniteStr = await StorageNative.getBestScoreWithinInfinite();
        var bestScoreWithinInfinite = JSON.parse(bestScoreWithinInfiniteStr);
        if (bestScoreWithinInfinite.code == 0) {
            console.log("===bestScoreWithinInfinite: " + bestScoreWithinInfinite.result);
            Config.BestScoreWithinInfinite = bestScoreWithinInfinite.result;
        }

        // 进入经典模式
        if (Config.CurrentGameMode == Constant.MODE_CLASSIC) {
            this.currentMode = 0;
            this.enterClassicsMode();
        } else {
            this.currentMode = 1;
            this.enterInfiniteMode();
        }
        //配置项数据

        let columnCount = Config.GRIDColumnCount;
        this.diffcults[0].checked = this.currentMode == 0 && columnCount == 4;
        this.diffcults[1].checked = this.currentMode == 0 && columnCount == 5;
        this.diffcults[2].checked = this.currentMode == 0 && columnCount == 6;

        let volumnState = Config.VolumeState;

        this.sounds[0].checked = volumnState;
        this.sounds[1].checked = !volumnState;

        this.achievements = Config.GetGoalTime == 0 ? strings.achievements : `${Config.GetGoalTime}`;
    },
    enterClassicsMode() {
        this.currentModeDesc = `${strings.game_mode_classics}`;
        Config.haveCheat = false;
        Config.CurrentGameMode = Constant.MODE_CLASSIC;
        for (var i = 0; i < this.diffcults.length; i++) {
            if (Config.GRIDColumnCount == this.diffcults[i].level) {
                this.diffcults[i].checked = true;
            } else {
                this.diffcults[i].checked = false;
            }
        }
        // 保存游戏模式
        StorageNative.putCurrentGameMode(Constant.MODE_CLASSIC);
        this.bestScore = Config.BestScore;
        this.bestScoreTitle = `最高分(${Config.GRIDColumnCount})`;
        let _this = this;
        StorageNative.getCurrentScore().then(data => {
            var obj = JSON.parse(data);
            if (obj.code == 0) {
                _this.currentScore = obj.result;
            }
        }).catch(err => {
            console.log(err);
        });
        this.$child('gameview').initView(constants.MODE_CLASSIC);
    },
    enterInfiniteMode() {
        this.currentModeDesc = `${strings.game_mode_infinite}`;
        //重置游戏难度选择
        for (var i = 0; i < this.diffcults.length; i++) {
            this.diffcults[i].checked = false;
        }
        // 进入无限模式
        Config.haveCheat = false;
        Config.CurrentGameMode = Constant.MODE_INFINITE;
        // 保存游戏模式
        StorageNative.putCurrentGameMode(Constant.MODE_INFINITE);
        this.bestScore = Config.BestScoreWithinInfinite;
        this.bestScoreTitle = `${strings.tv_best_score_infinite}`;
        let _this = this;
        StorageNative.getCurrentScoreWithinInfinite().then(data => {
            var obj = JSON.parse(data);
            if (obj.code == 0) {
                _this.currentScore = obj.result;
            }
        }).catch(err => {
            console.log(err);
        });
        this.$child('gameview').initView(constants.MODE_INFINITE);
    },
//更新得分，子控件回调方法
    updateScore(params) {
        console.log("===score:" + (JSON.stringify(params)));
        var score = params.detail;
        // 获取历史分数
        var totalScore = parseInt(this.currentScore) + score;
        //保存数据
        this.saveCurrentScore(totalScore);
        this.recordScore(totalScore);
    },
    saveCurrentScore(score) {
        if (Config.CurrentGameMode == Constant.MODE_CLASSIC) {
            StorageNative.putCurrentScore(score);
        } else {
            StorageNative.putCurrentScoreWithinInfinite(score);
        }
    },
    recordScore(score) {
        this.currentScore = score;
        // 当前分数大于最高分
        let _this = this;
        if (Config.CurrentGameMode == Constant.MODE_CLASSIC) {
            if (score > Config.BestScore) {
                _this.updateBestScore(score);
            }
        } else if (Config.CurrentGameMode == Constant.MODE_INFINITE) {
            if (score > Config.BestScoreWithinInfinite) {
                _this.updateBestScore(score);
            }

        }
    },
// 更新最高分
    updateBestScore(newScore) {
        this.bestScore = newScore;
        if (Config.CurrentGameMode == Constant.MODE_CLASSIC) {
            console.log("=== MODE_CLASSIC" + (typeof newScore))
            Config.BestScore = newScore;
            StorageNative.putBestScore(newScore);
        } else if (Config.CurrentGameMode == Constant.MODE_INFINITE) {
            console.log("=== MODE_INFINITE")
            Config.BestScoreWithinInfinite = newScore;
            StorageNative.putBestScoreWithinInfinite(newScore);
        }
    },
    saveGameProgress() {
        let fileName = Config.getTableName();
        // 保存新的数据
        let data = this.$child('gameview').getCurrentProcess();
        if (data.length > 2) {
            console.log("===data:" + data);
            StorageNative.putTableData(fileName, JSON.stringify(data));
        }
    },
    onBackPress() {
        this.saveGameProgress();
    },
    onDestroy() {
        this.saveGameProgress();
    },
    changeMode() {
        this.$element('change_mode_dialog').show();
    },
    closeChangeModeDialog() {
        this.$element('change_mode_dialog').close();
    },
    confirmChangeModeDialog() {
        this.$element('change_mode_dialog').close();
        this.currentMode = this.currentMode == 0 ? 1 : 0;
        if (this.currentMode == 0) {
            this.enterClassicsMode();
        } else {
            this.enterInfiniteMode();
        }
    },
    changeDiff(level) {
        if (this.currentMode == 0) {
            this.tempDifficultySelected = level;
            // this.diffcults[0].checked = level == 4;
            // this.diffcults[1].checked = level == 5;
            // this.diffcults[2].checked = level == 6;
        }
    },
    changeSoundState(state) {
        this.tempSoundsSelected
        if (state == "open") {
            this.tempSoundsSelected = 0;
            //            this.sounds[0].checked = true;
            //            this.sounds[1].checked = false;
        } else {
            this.tempSoundsSelected = 1;
            //            this.sounds[0].checked = false;
            //            this.sounds[1].checked = true;
        }
    },
    gameOver(params) {
        console.log("=== gameOver: " + JSON.stringify(params));
        var result = params.detail;
        if(result == "ACTION_WIN") {
            this.gameOverResult = "You Win!";
        }else {
            this.gameOverResult = "You Lose!";
        }
        this.showEndGameDialog();
    },
    showEndGameDialog() {
        this.$element('end_dialog').show();
    },
    closeEndGameDialog() {
        this.isNeedSave = false;
        //重置当前分数
        this.currentScore = 0;
        this.saveCurrentScore(0);
        //清空游戏数据
        let fileName = Config.getTableName();
        StorageNative.putTableData(fileName, "");
        this.$element('end_dialog').close();
    },
    clickGoOn() {
        this.isNeedSave = true;
        this.$child('gameview').resetGame();
        //重置当前分数
        this.currentScore = 0;
        this.saveCurrentScore(0);
        //清空游戏数据
        let fileName = Config.getTableName();
        StorageNative.putTableData(fileName, "");
        this.$child('gameview').initView(Config.CurrentGameMode);
        this.$element('reset-dialog').close();
    },
    showResetDialog() {
        this.$element('reset-dialog').show();
    },
    closeResetDialog() {
        this.$element('reset-dialog').close();
    },
    reset() {
        this.$element('reset-dialog').close();
        Config.haveCheat = false;
        this.$child('gameview').resetGame();
        //重置当前分数
        this.currentScore = 0;
        this.saveCurrentScore(0);
        //清空游戏数据
        let fileName = Config.getTableName();
        StorageNative.putTableData(fileName, "");
    },
    showDialog(e) {
        this.$element('config-dialog').show()
    },
    cancelDialog() {
        this.tempDifficultySelected = 0;
        this.tempSoundsSelected = -1;
    },
    async confirmDialog(e) {
        Config.haveCheat = false;
        //音效设置
        if (this.tempSoundsSelected >= 0) {
            for (var i = 0; i < this.sounds.length; i++) {
                this.sounds[i].checked = this.tempSoundsSelected == i;
            }
            let volumeState = !this.sounds[1].checked;
            if (volumeState != Config.VolumeState) {
                StorageNative.putGameVolume(volumeState);
                Config.VolumeState = volumeState;
            }
        }

        //游戏难度设置
        if (this.currentMode == 0) {
            if (this.tempDifficultySelected > 0) {
                for (var i = 0; i < this.diffcults.length; i++) {
                    this.diffcults[i].checked = this.tempDifficultySelected == this.diffcults[i].level;
                }
                let columnCount = 4;
                for (var i = 0; i < this.diffcults.length; i++) {
                    if (this.diffcults[i].checked) {
                        columnCount = this.diffcults[i].level;
                        break;
                    }
                }
                if (columnCount != Config.GRIDColumnCount) {
                    Config.GRIDColumnCount = columnCount;
                    this.bestScoreTitle = `最高分(${Config.GRIDColumnCount})`;
                    this.$child('gameview').initView(Constant.MODE_CLASSIC);
                    var result = await StorageNative.getCurrentScore();
                    var obj = JSON.parse(result);
                    if (obj.code == 0) {
                        this.currentScore = obj.result;
                    }
                    var bestScoreStr = await StorageNative.getBestScore();
                    var bestScoreObj = JSON.parse(bestScoreStr);
                    if (bestScoreObj.code == 0) {
                        this.bestScore = bestScoreObj.result;
                        Config.BestScore = this.bestScore;
                    }
                    StorageNative.putGameDifficulty(columnCount);
                }
            }
        }
        this.$element('config-dialog').close()
        this.tempDifficultySelected = 0;
        this.tempSoundsSelected = -1;
    },
}
